<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0,viewport-fit=cover"><title>ShardingSphere Narayana XA 事务不回滚问题定位 | flyingzc's blog</title><meta name="author" content="flyingzc"><meta name="copyright" content="flyingzc"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="ShardingSphere Narayana XA 事务不回滚问题定位问题背景用户反馈，在使用 ShardingSphere + Narayana 执行 XA 事务时，发生报错：java.sql.SQLException: javax.transaction.RollbackException: TransactionImple.enlistResource - ARJUNA016064: Th">
<meta property="og:type" content="article">
<meta property="og:title" content="ShardingSphere Narayana XA 事务不回滚问题定位">
<meta property="og:url" content="https://flyingzc.github.io/articles/shardingsphere/ShardingSphere-Narayana-XA%E4%BA%8B%E5%8A%A1%E4%B8%8D%E5%9B%9E%E6%BB%9A%E9%97%AE%E9%A2%98%E5%AE%9A%E4%BD%8D.html">
<meta property="og:site_name" content="flyingzc&#39;s blog">
<meta property="og:description" content="ShardingSphere Narayana XA 事务不回滚问题定位问题背景用户反馈，在使用 ShardingSphere + Narayana 执行 XA 事务时，发生报错：java.sql.SQLException: javax.transaction.RollbackException: TransactionImple.enlistResource - ARJUNA016064: Th">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://flyingzc.github.io/images/zc-icon.jpeg">
<meta property="article:published_time" content="2024-02-28T16:00:00.000Z">
<meta property="article:modified_time" content="2025-01-21T01:51:41.214Z">
<meta property="article:author" content="flyingzc">
<meta property="article:tag" content="Transaction">
<meta property="article:tag" content="Narayana">
<meta property="article:tag" content="ShardingSphere">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://flyingzc.github.io/images/zc-icon.jpeg"><script type="application/ld+json">{
  "@context": "https://schema.org",
  "@type": "BlogPosting",
  "headline": "ShardingSphere Narayana XA 事务不回滚问题定位",
  "url": "https://flyingzc.github.io/articles/shardingsphere/ShardingSphere-Narayana-XA%E4%BA%8B%E5%8A%A1%E4%B8%8D%E5%9B%9E%E6%BB%9A%E9%97%AE%E9%A2%98%E5%AE%9A%E4%BD%8D.html",
  "image": "https://flyingzc.github.io/images/zc-icon.jpeg",
  "datePublished": "2024-02-28T16:00:00.000Z",
  "dateModified": "2025-01-21T01:51:41.214Z",
  "author": [
    {
      "@type": "Person",
      "name": "flyingzc",
      "url": "https://flyingzc.github.io/"
    }
  ]
}</script><link rel="shortcut icon" href="/images/zc-icon.jpeg"><link rel="canonical" href="https://flyingzc.github.io/articles/shardingsphere/ShardingSphere-Narayana-XA%E4%BA%8B%E5%8A%A1%E4%B8%8D%E5%9B%9E%E6%BB%9A%E9%97%AE%E9%A2%98%E5%AE%9A%E4%BD%8D.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><meta name="google-site-verification" content="DentpX3LnP_WNgEeFnNIcTZZky-Bby-zL-uI_9GqTAw"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css"><script>
    (() => {
      
    const saveToLocal = {
      set: (key, value, ttl) => {
        if (!ttl) return
        const expiry = Date.now() + ttl * 86400000
        localStorage.setItem(key, JSON.stringify({ value, expiry }))
      },
      get: key => {
        const itemStr = localStorage.getItem(key)
        if (!itemStr) return undefined
        const { value, expiry } = JSON.parse(itemStr)
        if (Date.now() > expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return value
      }
    }

    window.btf = {
      saveToLocal,
      getScript: (url, attr = {}) => new Promise((resolve, reject) => {
        const script = document.createElement('script')
        script.src = url
        script.async = true
        Object.entries(attr).forEach(([key, val]) => script.setAttribute(key, val))
        script.onload = script.onreadystatechange = () => {
          if (!script.readyState || /loaded|complete/.test(script.readyState)) resolve()
        }
        script.onerror = reject
        document.head.appendChild(script)
      }),
      getCSS: (url, id) => new Promise((resolve, reject) => {
        const link = document.createElement('link')
        link.rel = 'stylesheet'
        link.href = url
        if (id) link.id = id
        link.onload = link.onreadystatechange = () => {
          if (!link.readyState || /loaded|complete/.test(link.readyState)) resolve()
        }
        link.onerror = reject
        document.head.appendChild(link)
      }),
      addGlobalFn: (key, fn, name = false, parent = window) => {
        if (!false && key.startsWith('pjax')) return
        const globalFn = parent.globalFn || {}
        globalFn[key] = globalFn[key] || {}
        globalFn[key][name || Object.keys(globalFn[key]).length] = fn
        parent.globalFn = globalFn
      }
    }
  
      
      const activateDarkMode = () => {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      const activateLightMode = () => {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }

      btf.activateDarkMode = activateDarkMode
      btf.activateLightMode = activateLightMode

      const theme = saveToLocal.get('theme')
    
          theme === 'dark' ? activateDarkMode() : theme === 'light' ? activateLightMode() : null
        
      
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        document.documentElement.classList.toggle('hide-aside', asideStatus === 'hide')
      }
    
      
    const detectApple = () => {
      if (/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)) {
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
  
    })()
  </script><script async="async" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script><script>(adsbygoogle = window.adsbygoogle || []).push({
  google_ad_client: '',
  enable_page_level_ads: 'true'
});</script><script>const GLOBAL_CONFIG = {
  root: '/',
  algolia: undefined,
  localSearch: undefined,
  translate: undefined,
  highlight: {"plugin":"highlight.js","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false,"highlightFullpage":false,"highlightMacStyle":false},
  copy: {
    success: '复制成功',
    error: '复制失败',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  dateSuffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'null',
  Snackbar: undefined,
  infinitegrid: {
    js: 'https://cdn.jsdelivr.net/npm/@egjs/infinitegrid/dist/infinitegrid.min.js',
    buttonText: '加载更多'
  },
  isPhotoFigcaption: false,
  islazyloadPlugin: false,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: false,
  },
  autoDarkmode: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'ShardingSphere Narayana XA 事务不回滚问题定位',
  isHighlightShrink: false,
  isToc: true,
  pageType: 'post'
}</script><link rel="stylesheet" href="/self/github-dark.css"><meta name="generator" content="Hexo 7.0.0"></head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img text-center"><img src="/images/zc-icon.jpeg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data text-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">84</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">36</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">29</div></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于我</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header"><nav id="nav"><span id="blog-info"><a class="nav-site-title" href="/"><span class="site-name">flyingzc's blog</span></a><a class="nav-page-title" href="/"><span class="site-name">ShardingSphere Narayana XA 事务不回滚问题定位</span></a></span><div id="menus"><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于我</span></a></div></div><div id="toggle-menu"><span class="site-page"><i class="fas fa-bars fa-fw"></i></span></div></div></nav><div id="post-info"><h1 class="post-title">ShardingSphere Narayana XA 事务不回滚问题定位</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2024-02-28T16:00:00.000Z" title="发表于 2024-02-29 00:00:00">2024-02-29</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2025-01-21T01:51:41.214Z" title="更新于 2025-01-21 09:51:41">2025-01-21</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Transaction/">Transaction</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title=""><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">浏览量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="container post-content" id="article-container"><h1 id="ShardingSphere-Narayana-XA-事务不回滚问题定位"><a href="#ShardingSphere-Narayana-XA-事务不回滚问题定位" class="headerlink" title="ShardingSphere Narayana XA 事务不回滚问题定位"></a>ShardingSphere Narayana XA 事务不回滚问题定位</h1><h2 id="问题背景"><a href="#问题背景" class="headerlink" title="问题背景"></a>问题背景</h2><p>用户反馈，在使用 ShardingSphere + Narayana 执行 XA 事务时，发生报错：<code>java.sql.SQLException: javax.transaction.RollbackException: TransactionImple.enlistResource - ARJUNA016064: The transaction is in an invalid state!</code>。<br>这个报错的含义简单来说就是这个事务已经在其他地方被标记成<code>只可回滚</code>了，不能再进行后续其他的操作。报错信息如下：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><code class="hljs plaintext">Caused by: java.sql.SQLException: javax.transaction.RollbackException: TransactionImple.enlistResource - ARJUNA016064: The transaction is in an invalid state!<br>        at org.apache.shardingsphere.transaction.xa.XAShardingSphereTransactionManager.getConnection(XAShardingSphereTransactionManager.java:101)<br>        at org.apache.shardingsphere.transaction.ConnectionTransaction.getConnection(ConnectionTransaction.java:102)<br>        at org.apache.shardingsphere.driver.jdbc.core.connection.DriverDatabaseConnectionManager.createConnection(DriverDatabaseConnectionManager<br>.java:416)<br>        at org.apache.shardingsphere.driver.jdbc.core.connection.DriverDatabaseConnectionManager.createConnections(DriverDatabaseConnectionManage<br>r.java:383)<br>        at org.apache.shardingsphere.driver.jdbc.core.connection.DriverDatabaseConnectionManager.getConnections(DriverDatabaseConnectionManager.j<br>ava:357)<br>        at org.apache.shardingsphere.driver.jdbc.core.connection.DriverDatabaseConnectionManager.getConnections(DriverDatabaseConnectionManager.j<br>ava:338)<br>        at org.apache.shardingsphere.infra.executor.sql.prepare.driver.DriverExecutionPrepareEngine.group(DriverExecutionPrepareEngine.java:89)<br>        at org.apache.shardingsphere.infra.executor.sql.prepare.AbstractExecutionPrepareEngine.prepare(AbstractExecutionPrepareEngine.java:73)<br>        at org.apache.shardingsphere.infra.executor.sql.prepare.AbstractExecutionPrepareEngine.prepare(AbstractExecutionPrepareEngine.java:61)<br>        at org.apache.shardingsphere.driver.jdbc.core.statement.ShardingSpherePreparedStatement.createExecutionGroupContext(ShardingSpherePrepare<br>dStatement.java:764)<br>        at org.apache.shardingsphere.driver.jdbc.core.statement.ShardingSpherePreparedStatement.useDriverToExecute(ShardingSpherePreparedStatement.java:717)<br>        at org.apache.shardingsphere.driver.jdbc.core.statement.ShardingSpherePreparedStatement.executeWithExecutionContexts(ShardingSpherePreparedStatement.java:658)<br>        at org.apache.shardingsphere.driver.jdbc.core.statement.ShardingSpherePreparedStatement.execute(ShardingSpherePreparedStatement.java:631)<br>        at org.apache.ibatis.executor.statement.PreparedStatementHandler.update(PreparedStatementHandler.java:44)<br>        at org.apache.ibatis.executor.statement.RoutingStatementHandler.update(RoutingStatementHandler.java:69)<br>        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)<br></code></pre></td></tr></table></figure>

<h2 id="问题分析"><a href="#问题分析" class="headerlink" title="问题分析"></a>问题分析</h2><p>观察日志里有调用 setRollbackOnly 方法的日志，通过查看 setRollbackOnly 方法的调用链路，再结合报错是在 <code>getConnection</code> 时报的，那么调用 setRollbackOnly 方法应该发生在<code>getConnection</code>之前，极有可能是 <code>enlistResource</code> 地方报的。<br><img src="/images/img-20240123115238.png"></p>
<p>通过查看 <code>enlistResource</code> 方法的逻辑，注释里写的是 xa start 语句没执行成功时会调用 <code>markRollbackOnly</code> 标识事务只可回滚。<br><img src="/images/img-20240123115315.png"></p>
<p>查看 narayana trace 日志，发现 <code>enlistResource</code> 操作前后有一个可疑日志。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs log">-- xid unset<br>[2024-01-23 11:10:08,001] [com.arjuna.ats.internal.jta.resources.arjunacore.XAResourceRecord],[&lt;init&gt;],[XNIO-1 task-1],[INFO],[XAResourceRecord.XAResourceRecord ( ARJUNA016100: Xid unset, org.apache.shardingsphere.transaction.xa.spi.SingleXAResource@5c6c9ab9 ), record id=0:ffff0acf077d:837d:65af2e0d:4]<br><br>-- set rollback only<br>[2024-01-23 11:10:08,357],[eciqs-core],[com.arjuna.ats.internal.jta.transaction.arjunacore.TransactionImple],[setRollbackOnly],[XNIO-1 task-1],[INFO],[TransactionImple.setRollbackOnly]<br><br>-- 后续自动执行回滚操作日志<br>[2024-01-23 11:10:09,081],[eciqs-core],[com.arjuna.ats.internal.jta.transaction.arjunacore.BaseTransaction],[rollback],[XNIO-1 task-1],[INFO],[BaseTransaction.rollback]<br><br>[2024-01-23 11:10:09,081],[eciqs-core],[com.arjuna.ats.internal.jta.transaction.arjunacore.TransactionImple],[rollbackAndDisassociate],[XNIO-1 task-1],[INFO],[TransactionImple.rollbackAndDisassociate]<br><br>[2024-01-23 11:10:09,081],[eciqs-core],[com.arjuna.ats.arjuna.coordinator.BasicAction],[Abort],[XNIO-1 task-1],[INFO],[BasicAction::Abort() for action-id 0:ffff0acf077d:837d:65af2e0d:2]<br></code></pre></td></tr></table></figure>

<p>日志显示的是 <code>ARJUNA016100: Xid unset</code>,正常日志应该如下：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs log">2024-01-23 11:48:33.341 [main] TRACE com.arjuna.ats.jta - XAResourceRecord.XAResourceRecord ( &lt; formatId=131077, gtrid_length=29, bqual_length=36, tx_uid=0:ffff7f000101:90ab:65af3711:2, node_name=1, branch_uid=0:ffff7f000101:90ab:65af3711:3, subordinatenodename=null, eis_name=0 &gt;, com.zc.transaction.xa.SingleXACtrlResource@1fc793c2 ), record id=0:ffff7f000101:90ab:65af3711:4<br></code></pre></td></tr></table></figure>

<h3 id="ARJUNA016100-Xid-unset"><a href="#ARJUNA016100-Xid-unset" class="headerlink" title="ARJUNA016100: Xid unset"></a>ARJUNA016100: Xid unset</h3><p>后续分析为什么会出现<code>ARJUNA016100: Xid unset</code> 异常。<br>搜索 ARJUNA016100 错误码，是在 xidImple.toString 里调用的。</p>
<p>原因，比如一个 xa 事务涉及两个 xa resources,在执行第一个 resource enlist 时候，由于 xid 有问题，start xid 在 mysql 上执行失败了，然后 Naryana 自己调用 <code>com.arjuna.ats.internal.jta.transaction.arjunacore.TransactionImple#setRollbackOnly</code> 方法将当前全局事务状态设置为 <code>ActionStatus.ABORT_ONLY</code> 状态。<br>那么当事务内第二个 xa resource 执行 enlist resource 操作时，由于当前事务已经标记为只回滚，所以执行报错。也就是最开始日志里报的错：<code>java.sql.SQLException: javax.transaction.RollbackException: TransactionImple.enlistResource - ARJUNA016064: The transaction is in an invalid state!</code><br>相关代码如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-type">boolean</span> <span class="hljs-title function_">enlistResource</span><span class="hljs-params">(XAResource xaRes, Object[] params)</span>  <br>       <span class="hljs-keyword">throws</span> RollbackException, IllegalStateException,  <br>       jakarta.transaction.SystemException  <br>&#123;  <br>  <span class="hljs-comment">// ...</span><br>    <span class="hljs-type">int</span> <span class="hljs-variable">status</span> <span class="hljs-operator">=</span> getStatus();  <br>  <br>    <span class="hljs-keyword">switch</span> (status)  <br>    &#123;    <br>    <span class="hljs-comment">// jakarta.transaction.Status.STATUS_MARKED_ROLLBACK 对应上面的 ActionStatus.ABORT_ONLY 状态，报错 invalid。</span><br>    <span class="hljs-keyword">case</span> jakarta.transaction.Status.STATUS_MARKED_ROLLBACK:  <br>       <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">RollbackException</span>(  <br>             <span class="hljs-string">&quot;TransactionImple.enlistResource - &quot;</span> + jtaLogger.i18NLogger.get_transaction_arjunacore_invalidstate() );  <br>    <span class="hljs-keyword">case</span> jakarta.transaction.Status.STATUS_ACTIVE:  <br>       <span class="hljs-keyword">break</span>;  <br>    <span class="hljs-keyword">default</span>:  <br>       <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">IllegalStateException</span>( jtaLogger.i18NLogger.get_transaction_arjunacore_inactive() );  <br>    &#125;<br></code></pre></td></tr></table></figure>

<p>当出现报错后，后续 narayana 会自动执行回滚操作，参考 narayana 日志。</p>
<h3 id="XID-为空原因"><a href="#XID-为空原因" class="headerlink" title="XID 为空原因"></a>XID 为空原因</h3><p>为什么 xid 会为空。<br>这个 xid 为空的报错是在 <code>com.arjuna.ats.jta.xa.XidImple#toString</code> 方法中报的，实际上是 <code>com.arjuna.ats.jta.xa.XidImple#_theXid</code> 为空导致。<br>在 XidImple 所有构造方法中打断点，看创建 xid 过程，哪里导致 <code>_theXid</code> 属性为空。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-title function_">XidImple</span><span class="hljs-params">(Uid id, <span class="hljs-type">boolean</span> branch, Integer eisName)</span> &#123;  <br>    <span class="hljs-keyword">try</span> &#123;  <br>        <span class="hljs-comment">// 可以看到如果创建 _theXid 失败，则捕获了异常</span><br>       _theXid = XATxConverter.getXid(id, branch, eisName);  <br>    &#125; <span class="hljs-keyword">catch</span> (Exception e) &#123;  <br>       _theXid = <span class="hljs-literal">null</span>;  <br>  <br>       jtaLogger.i18NLogger.warn_cant_create_xid_of_branch(id, branch, eisName, e);  <br>  <br>       <span class="hljs-comment">// abort or throw exception?  </span><br>    &#125;  <br>    hashCode = getHash(_theXid);  <br>&#125;<br></code></pre></td></tr></table></figure>

<p>后续 debug 看日常信息，发现 xid 为 null,异常信息里有 <code>ARJUNA016111: The node identifier cannot be null</code> 信息，这个明显是没有读取到<code> jbossts.xml</code> 配置文件导致的报错。</p>
<p>后续通过修改 Transaction Rule, 尝试刷新配置，发现错误依然存在。Debug 发现没有读取到 jbossts.xml 配置文件导致。</p>
<p>使用 arthas 查看应用里 ShardingSphere-JDBC 的 TransactionRule 属性正常，说明 Rule 正常刷新。<br>但是 arthas 查看 ObjectStoreEnvironmentBean 里的 jdbc 属性为空，说明没有读取到 jbossts.xml 配置文件。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs shell">sc -d *TransactionRule<br>vmtool --action getInstances -c 368239c8 --className org.apache.shardingsphere.transaction.rule.TransactionRule --limit 10 -x 2<br><br>sc -d *ObjectStoreEnvironmentBean<br>vmtool --action getInstances -c 368239c8 --className com.arjuna.ats.arjuna.common.ObjectStoreEnvironmentBean --limit 10 -x 2<br></code></pre></td></tr></table></figure>

<p>然后 Debug Narayana 启动逻辑，发现应用目录下并没有 <code>jbossts.xml</code> 配置文件。咨询用户发现应用系统每次部署启动阶段会清除目录下的所有文件，导致读取失败。</p>
<h2 id="问题解决"><a href="#问题解决" class="headerlink" title="问题解决"></a>问题解决</h2><p>用于该应用在启动阶段会清理目录下的配置文件，将 <code>jbossts.xml</code> 放到其他 Narayana 可以读取到的目录下即可。</p>
<link rel="stylesheet" href="https://fastly.jsdelivr.net/npm/markmap-toolbar@0.18.10/dist/style.css"><script src="https://fastly.jsdelivr.net/npm/d3@7"></script><script src="https://fastly.jsdelivr.net/npm/markmap-view@0.18.10"></script><script src="https://fastly.jsdelivr.net/npm/markmap-toolbar@0.18.10"></script>
<link rel="stylesheet" href="/css/markmap.css">

<script src="/js/markmap.js"></script>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta"><i class="fas fa-circle-user fa-fw"></i>文章作者: </span><span class="post-copyright-info"><a href="https://flyingzc.github.io">flyingzc</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta"><i class="fas fa-square-arrow-up-right fa-fw"></i>文章链接: </span><span class="post-copyright-info"><a href="https://flyingzc.github.io/articles/shardingsphere/ShardingSphere-Narayana-XA%E4%BA%8B%E5%8A%A1%E4%B8%8D%E5%9B%9E%E6%BB%9A%E9%97%AE%E9%A2%98%E5%AE%9A%E4%BD%8D.html">https://flyingzc.github.io/articles/shardingsphere/ShardingSphere-Narayana-XA%E4%BA%8B%E5%8A%A1%E4%B8%8D%E5%9B%9E%E6%BB%9A%E9%97%AE%E9%A2%98%E5%AE%9A%E4%BD%8D.html</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta"><i class="fas fa-circle-exclamation fa-fw"></i>版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来源 <a href="https://flyingzc.github.io" target="_blank">flyingzc's blog</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/Transaction/">Transaction</a><a class="post-meta__tags" href="/tags/Narayana/">Narayana</a><a class="post-meta__tags" href="/tags/ShardingSphere/">ShardingSphere</a></div><div class="post-share"><div class="social-share" data-image="/images/zc-icon.jpeg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><a class="pagination-related" href="/articles/shardingsphere/ShardingSphere-XA%E4%BA%8B%E5%8A%A1%E6%97%A0%E6%B3%95%E6%81%A2%E5%A4%8D%E9%97%AE%E9%A2%98.html" title="ShardingSphere-XA事务无法恢复问题定位"><div class="cover" style="background: var(--default-bg-color)"></div><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2024-02-28</div><div class="info-item-2">ShardingSphere-XA事务无法恢复问题定位</div></div><div class="info-2"><div class="info-item-1">ShardingSphere-XA事务无法恢复问题定位问题背景在测试 ShardingSphere-Proxy 使用达梦数据库开启 XA 事务进行压测期间，kill 掉达梦数据库，等一段时间再重启达梦数据库，最终未完成的 XA 事务无法恢复，数据产生不一致。查看达梦上的 xid 一直有残留，没有被处理。使用 ShardingSphere-Proxy 结合其他主流数据库进行测试时无该问题。 通过日志可以看到在压测期间，挂掉达梦数据库之后，有大量连接报错。节选错误日志如下：比如下面这段日志，在执行 xa end 操作时，因为达梦数据库连接不上，达梦驱动报错如下： 1234567891011121314151617181920212223242526272829[WARN ] 2024-01-29 11:11:19.867 [Connection-82-ThreadExecutor] com.arjuna.ats.jta - ARJUNA016041: prepare on &lt; formatId=131077, gtrid_length=64, bqual_length=36,...</div></div></div></a><a class="pagination-related" href="/articles/narayana/narayana01-init.html" title="Narayana 事务管理器初始化流程"><div class="cover" style="background: var(--default-bg-color)"></div><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2023-12-06</div><div class="info-item-2">Narayana 事务管理器初始化流程</div></div><div class="info-2"><div class="info-item-1">事务管理器初始化流程总体流程12345678910创建 TransactionManagerImple    创建事务管理器对象读取 narayana 的 xml 配置，进行属性赋值获取 recovery 模块    加载恢复模块事务恢复日志的初始化初始化事务日志存储服务    JDBC方式存储        建表	文件方式存储  创建 TransactionManager 流程Narayana 会通过 BeanPopulator 反射创建对应的 TransactionManager 实例，并读取用户自定义的 xml 属性反射赋值到 TransactionManager 实例里。 1TransactionManager transactionManager =...</div></div></div></a><a class="pagination-related" href="/articles/narayana/narayana02-init-jdbc.html" title="Narayana启动-注册恢复模块流程"><div class="cover" style="background: var(--default-bg-color)"></div><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2023-12-07</div><div class="info-item-2">Narayana启动-注册恢复模块流程</div></div><div class="info-2"><div class="info-item-1">Narayana启动-注册恢复模块流程使用代码12// narayana 在启动阶段使用如下 api 加载恢复模块XARecoveryModulexaRecoveryModule = XARecoveryModule.getRegisteredXARecoveryModule();  总体流程1234567891011121314151617注册恢复模块    反射创建 RecoveryEnvironmentBean 配置信息实例    加载 RecoveryActivators    启动 RecoveryActivators    初始化 PeriodicRecovery        设置恢复状态 INACTIVE        设置恢复mode ENABLED    加载恢复模块，module包括:    1.com.arjuna.ats.internal.arjuna.recovery.AtomicActionRecoveryModule   ...</div></div></div></a><a class="pagination-related" href="/articles/narayana/narayana03-begin.html" title="Narayana 事务 begin 流程"><div class="cover" style="background: var(--default-bg-color)"></div><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2023-12-08</div><div class="info-item-2">Narayana 事务 begin 流程</div></div><div class="info-2"><div class="info-item-1">Narayana 事务 begin 流程整体流程12345检查事务状态获取超时时间创建事务对象    事务对象设置到 ThreadLocal 中,和当前线程绑定    插入事务测超时时间监控  使用 API123TransactionManager transactionManager = jtaPropertyManager.getJTAEnvironmentBean().getTransactionManager();// 开启全局事务transactionManager.begin();  调用链路123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869internal.jta.transaction.arjunacore.BaseTransaction#begin开启事务   ...</div></div></div></a><a class="pagination-related" href="/articles/narayana/narayana04-enlistResource.html" title="Narayana 事务资源注册流程"><div class="cover" style="background: var(--default-bg-color)"></div><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2023-12-08</div><div class="info-item-2">Narayana 事务资源注册流程</div></div><div class="info-2"><div class="info-item-1">Narayana enlistResource流程XA 事务内每个物理连接执行第一条物理 sql 之前,需要执行 xa start 操作开启每个RM分支上的 xa 事务,并将 xaResource 注册到 TransactionManager 里。 整体流程12345678910transaction.enlistResource(xaResource)    执行 XA start xid        遍历 resource 判断当前是 isNewRM        创建 xid        createRecord        theTransaction.add(abstractRecord)            record 添加到 BasicAction.RecordList 里        执行 xa start 语句,若失败重试            MysqlXAConnection#start    把 XAResource 缓存到 map  使用1234567// 获取 XADataSourceXADataSource xaDatasource =...</div></div></div></a><a class="pagination-related" href="/articles/narayana/narayana05-commit.html" title="Narayana 事务 Commit 流程"><div class="cover" style="background: var(--default-bg-color)"></div><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2023-12-11</div><div class="info-item-2">Narayana 事务 Commit 流程</div></div><div class="info-2"><div class="info-item-1">Narayana commit 流程整体流程123456789101112131415161718192021222324事务提交    判断是否能进行一阶段提交优化        若能一阶段提交            执行一阶段提交        否则            二阶段提交                prepare阶段                    执行 xa end                    执行 xa prepare                        xaResourceRecord 插入到 preparedList                            BasicAction#insertRecord                        更新状态 ActionStatus.COMMITTING                        保存状态，打包状态到 outputBuffer 里                            XAResourceRecord#save_state...</div></div></div></a></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info text-center"><div class="avatar-img"><img src="/images/zc-icon.jpeg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info-name">flyingzc</div><div class="author-info-description">不积跬步无以至千里<br/>不积小流无以成江海</div><div class="site-data"><a href="/archives/"><div class="headline">文章</div><div class="length-num">84</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">36</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">29</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/FlyingZC"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons"><a class="social-icon" href="https://github.com/FlyingZC" target="_blank" title="Github"><i class="fab fa-github" style="color: #24292e;"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">FlyingZC's Blog</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#ShardingSphere-Narayana-XA-%E4%BA%8B%E5%8A%A1%E4%B8%8D%E5%9B%9E%E6%BB%9A%E9%97%AE%E9%A2%98%E5%AE%9A%E4%BD%8D"><span class="toc-number">1.</span> <span class="toc-text">ShardingSphere Narayana XA 事务不回滚问题定位</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E9%97%AE%E9%A2%98%E8%83%8C%E6%99%AF"><span class="toc-number">1.1.</span> <span class="toc-text">问题背景</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E9%97%AE%E9%A2%98%E5%88%86%E6%9E%90"><span class="toc-number">1.2.</span> <span class="toc-text">问题分析</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#ARJUNA016100-Xid-unset"><span class="toc-number">1.2.1.</span> <span class="toc-text">ARJUNA016100: Xid unset</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#XID-%E4%B8%BA%E7%A9%BA%E5%8E%9F%E5%9B%A0"><span class="toc-number">1.2.2.</span> <span class="toc-text">XID 为空原因</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E9%97%AE%E9%A2%98%E8%A7%A3%E5%86%B3"><span class="toc-number">1.3.</span> <span class="toc-text">问题解决</span></a></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/articles/ignite/ignite03-transaction-begin.html" title="Apache Ignite 开启事务执行流程">Apache Ignite 开启事务执行流程</a><time datetime="2025-10-10T16:00:00.000Z" title="发表于 2025-10-11 00:00:00">2025-10-11</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/articles/ignite/ignite02-transaction.html" title="Apache Ignite 分布式事务原理">Apache Ignite 分布式事务原理</a><time datetime="2025-09-17T16:00:00.000Z" title="发表于 2025-09-18 00:00:00">2025-09-18</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/articles/ignite/ignite01-build.html" title="Apache Ignite IDEA 环境搭建">Apache Ignite IDEA 环境搭建</a><time datetime="2025-09-10T16:00:00.000Z" title="发表于 2025-09-11 00:00:00">2025-09-11</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/articles/druid/druid01-resultset-leak.html" title="ShardingSphere JDBC 使用 Druid 连接池 ResultSet 内存泄露分析">ShardingSphere JDBC 使用 Druid 连接池 ResultSet 内存泄露分析</a><time datetime="2025-06-30T16:00:00.000Z" title="发表于 2025-07-01 00:00:00">2025-07-01</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/articles/jmeter/jmeter01-shardingsphere.html" title="Jmeter 压测 ShardingSphere">Jmeter 压测 ShardingSphere</a><time datetime="2025-06-30T16:00:00.000Z" title="发表于 2025-07-01 00:00:00">2025-07-01</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2025 By flyingzc</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="日间和夜间模式切换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside-config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><div class="js-pjax"></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>